package com.javaspeak.designpatterns.go4.behavioural.mediator;

/**
 * This example application uses the Mediator pattern.
 * <p>
 * ChatUsers communicate with each other via a ChatMediator.  The ChatMediator
 * mediates between the ChatUsers.  Only the ChatMediator has a references to
 * all consumers and producers.  In this example the ChatUsers are both
 * consumers and producers: they can both send and receive messages.  A
 * ChatUser sends and receives a message via the ChatMediator.
 * <p>
 * Before a ChatUser can send a message a group must exist.  The ChatUser can
 * check whether a group exists and if it does not create one by calling the
 * createNewGroup(..) method on the ChatMediator. Once a group exists ChatUsers
 * can subscribe to the group.  ChatUsers can then send messages to the group
 * by calling the sendMessage(..) method on the ChatMediator.  The ChatMediator
 * in return calls receiveMessage(..) on each of the ChatUsers that is
 * subscribed to the group.
 *
 * @author John Dickerson
 */
public class ApplicationMediator {

    public void runExample(){

        // The chatMediator to pass through the constructor of each ChatUser
        ChatMediator chatMediator = new ChatMediatorImpl();

        ChatUser chatUserOne = new ChatUserImpl( chatMediator, "chatUserOne" );
        ChatUser chatUserTwo = new ChatUserImpl( chatMediator, "chatUserTwo" );
        ChatUser chatUserThree = new ChatUserImpl( chatMediator, "chatUserThree" );

        String[] groups = chatUserOne.getGroups();

        String groupName = "kite surfing";

        // ChatUserOne checks if the "kite surfing" group already exists
        // and creates one if it does not exist
        if ( ! chatUserOne.groupExists( groups , groupName ) ){

            chatUserOne.createNewGroup( groupName );
        }

        // three ChatUsers subscribe to the "kite surfing" group
        chatUserOne.subscribeToGroup( groupName );
        chatUserTwo.subscribeToGroup( groupName );
        chatUserThree.subscribeToGroup( groupName );

        // ChatUserOne sends a message to the group
        chatUserOne.sendMessage( groupName,
                "Kite meet at Shoreham, Saturday. Any one want to go?" );

        // ChatUserTwo sends a message to the group
        chatUserTwo.sendMessage( groupName, "Yes I would like to go" );

        // ChatUserThree sends a message to the group
        chatUserThree.sendMessage( groupName, "Count me in as well" );
    }


    public static void main( String args[] ){

        ApplicationMediator application = new ApplicationMediator();
        application.runExample();
    }
}
